package com.tx.admin.lifeday.controller;

import com.tx.AI.WeberTest;
import com.tx.admin.lifeday.pojo.po.LifeDay;
import com.tx.admin.lifeday.pojo.vo.LifeDayListVO;
import com.tx.core.common.enums.CommonResponseEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import com.tx.core.common.entity.ApiPageResult;
import com.tx.core.common.entity.ApiResult;
import com.tx.core.common.constant.GlobalConstant;
import com.tx.core.common.entity.PageResult;
import com.tx.core.common.entity.SelectIdsDTO;
import com.tx.admin.lifeday.service.LifeDayService;
import com.tx.admin.lifeday.pojo.dto.LifeDayCreateDTO;
import com.tx.admin.lifeday.pojo.dto.LifeDayUpdateDTO;
import com.tx.admin.lifeday.pojo.dto.LifeDayListDTO;
import com.tx.admin.lifeday.pojo.vo.LifeDayVO;
import com.tx.core.common.entity.ImportExcelDTO;
import jakarta.servlet.http.HttpServletResponse;

import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 生活记录每日表 Controller
 * </p>
 *
 * @author sz-admin
 * @since 2025-08-22
 */
@Tag(name =  "生活记录每日表")
@RestController
@RequestMapping("life-day")
@RequiredArgsConstructor
public class LifeDayController  {

    private final LifeDayService lifeDayService;

    @PostConstruct
    public void init() {
        String anser = WeberTest.getAnser("你好，AI佬！");
    }

    @PreDestroy
    public void destory() {
        WeberTest.destory();
    }

    @Operation(summary = "新增")
    @PostMapping
    public ApiResult<Void> create(@RequestBody LifeDayCreateDTO dto) {
        lifeDayService.create(dto);
        return ApiResult.success();
    }

    @Operation(summary = "全部新增")
    @PostMapping("create")
    public ApiResult<Void> createOneDay(@RequestBody LifeDayCreateDTO dto) {
        // 异步执行第一个任务
        CompletableFuture<Long> task1 = CompletableFuture.supplyAsync(() -> {
            try {
                return lifeDayService.createOneDay(dto);
            } catch (Exception e) {
                e.printStackTrace();
                CommonResponseEnum message = CommonResponseEnum.SELF.message(e.getMessage());
                message.message(e.getMessage());
                throw new RuntimeException(message.getMessage());  // 抛出异常以便后续处理
            }
        });


        // 异步执行第二个任务，使用 CompletableFuture.supplyAsync 来返回值
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            try {
                String answer = WeberTest.getAnser("目前体重81.2，身高174cm,请以下面的格式(仅一行显示并附加克数)生成减肥三餐\n" +
                        "早：\n" +
                        "中：\n" +
                        "晚：");
                return answer;  // 返回结果
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Error in task2: " + e.getMessage());
            }
        });

        try {
            // 同步等待这两个任务完成
            CompletableFuture.allOf(task1, task2).join();
            LifeDayUpdateDTO day =new LifeDayUpdateDTO();
            day.setId(task1.get());
            day.setExt2("早餐：" + task2.get().split("早餐：")[1]);
            lifeDayService.update(day);
        } catch (Exception e) {
            // 捕获任务中的异常
            return ApiResult.error(CommonResponseEnum.SELF.message(e.getMessage()));
        }


        return ApiResult.success();
    }

    @Operation(summary = "修改图片标签集合")
    @PostMapping("changePicture")
    public ApiResult<LifeDayCreateDTO> changePicture(@RequestBody LifeDayCreateDTO dto) {
        LifeDayCreateDTO lifeDayCreateDTO = null;
        try {
            lifeDayCreateDTO =  lifeDayService.changePicture(dto);
        }catch (Exception e){
            CommonResponseEnum message = CommonResponseEnum.SELF.message(e.getMessage());
            message.message(e.getMessage());
            return ApiResult.error(message);
        }
        return ApiResult.success(lifeDayCreateDTO);

    }

    @Operation(summary = "查近7天的报告列表")
    @GetMapping("list")
    public ApiResult<PageResult<LifeDayListVO>> daylist() {
        return ApiPageResult.success(lifeDayService.daylist());
    }


    @Operation(summary = "修改")
    @SaCheckPermission(value = "life.day.update")
    @PutMapping
    public ApiResult<Void> update(@RequestBody LifeDayUpdateDTO dto) {
        lifeDayService.update(dto);
        return ApiResult.success();
    }

    @Operation(summary = "删除")
    @SaCheckPermission(value = "life.day.remove")
    @DeleteMapping
    public ApiResult<Void> remove(@RequestBody SelectIdsDTO dto) {
        lifeDayService.remove(dto);
        return ApiResult.success();
    }

    @Operation(summary = "列表查询")
    @SaCheckPermission(value = "life.day.query_table")
    @GetMapping
    public ApiResult<PageResult<LifeDayVO>> list(LifeDayListDTO dto) {
        return ApiPageResult.success(lifeDayService.page(dto));
    }

    @Operation(summary = "详情")
    @SaCheckPermission(value = "life.day.query_table")
    @GetMapping("/{id}")
    public ApiResult<LifeDayVO> detail(@PathVariable Object id) {
        return ApiResult.success(lifeDayService.detail(id));
    }

    @Operation(summary = "导入")
    @Parameters({
      @Parameter(name = "file", description = "上传文件", schema = @Schema(type = "string", format = "binary"), required = true),
    })
    @SaCheckPermission(value = "life.day.import")
    @PostMapping("/import")
    public void importExcel(@ModelAttribute ImportExcelDTO dto) {
        lifeDayService.importExcel(dto);
    }

    @Operation(summary = "导出")
    @SaCheckPermission(value = "life.day.export")
    @PostMapping("/export")
    public void exportExcel(@RequestBody LifeDayListDTO dto, HttpServletResponse response) {
        lifeDayService.exportExcel(dto, response);
    }
}